package com.io.example.demoparent.arry;

import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 *   二维数据demo
 */
public class SparseArray {
    public static void main(String[] args) throws Exception {


        /**
         *      创建一个原始二维数组 11*11
         *      0:表示没有棋子，1表示黑子 2表示篮子
         */
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        System.out.println("原始的二维数组");
//        for (int[] row : chessArr1) {
//            for (int data : row) {
//
//                System.out.printf("%d\t", data);
//            }
//            System.out.println();
//        }

        transitionArray(chessArr1);


    }


    public static void transitionArray(int[][] arr) throws Exception {
        int sum = 0;
        //遍历二维数组，得到非0的数据

        for (int[] row : arr) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        int sparseArr[][] = new int[sum + 1][3];
        sparseArr[0][0] = arr.length;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 0;  //记录是第几个非0数据
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = arr[i][j];

                }
            }
        }
        System.out.println();
        System.out.println("得到的稀疏数组");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(sparseArr[i][0]).append("  ").append(sparseArr[i][1]).append("  ").append(sparseArr[i][2]).append("\r\n");
            writeFile(stringBuffer);
        }

        System.out.println();




    }


    //从键盘读入字符串，一次读取一整行，转化为大写，然后继续读取，知道读取到'e'或'exit'
    //思路： System.in --> 转换流 --> BufferedReader.readLine()
    public static void writeFile(StringBuffer s) throws  Exception {
        FileWriter  out=new FileWriter ("D:\\1.txt",true);
        BufferedWriter fileWriter = new BufferedWriter(out);
        fileWriter.write(s.toString());
        fileWriter.close();
    }






}
